import 'package:flutter/material.dart';

class TagFlowWidget extends StatefulWidget {
  final List<String> items;
  final int maxRows;
  final double spaceHorizontal;
  final double spaceVertical;
  final double itemHeight;
  final TextStyle? itemStyle;
  final Color selectedTextColor;
  final Color unselectedTextColor;
  // 新增：是否默认选中第一个标签（默认true，可外部控制）
  final bool defaultSelectFirst;
  final Function(String? selectedItem)? onSelectedChanged;

  const TagFlowWidget({
    super.key,
    required this.items,
    required this.maxRows,
    required this.itemHeight,
    this.spaceHorizontal = 0,
    this.spaceVertical = 0,
    this.itemStyle,
    this.selectedTextColor = Colors.blue,
    this.unselectedTextColor = Colors.grey,
    this.defaultSelectFirst = true, // 默认开启“选中第一个”
    this.onSelectedChanged,
  });

  @override
  TagFlowWidgetState createState() => TagFlowWidgetState();
}

class TagFlowWidgetState extends State<TagFlowWidget> {
  bool isExpanded = false;
  int? _selectedIndex; // 单选索引（默认将设为0）

  @override
  void initState() {
    super.initState();
    // 核心：默认选中第一个标签（需确保items不为空）
    if (widget.items.isNotEmpty && widget.defaultSelectFirst) {
      _selectedIndex = 0;
      // 初始选中时触发外部回调（同步初始状态）
      if (widget.onSelectedChanged != null) {
        widget.onSelectedChanged!(widget.items[0]);
      }
    }
  }

  // 单选切换逻辑（保持不变）
  void _toggleSingleSelection(int index) {
    setState(() {
      _selectedIndex = _selectedIndex == index ? null : index;
    });

    if (widget.onSelectedChanged != null) {
      final selectedItem = _selectedIndex != null
          ? widget.items[_selectedIndex!]
          : null;
      widget.onSelectedChanged!(selectedItem);
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final maxWidth = constraints.maxWidth;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: [
            Flow(
              delegate: TagFlowDelegate(
                maxRows: widget.maxRows,
                isExpanded: isExpanded,
                maxWidth: maxWidth,
                itemHeight: widget.itemHeight,
                spaceHorizontal: widget.spaceHorizontal,
                spaceVertical: widget.spaceVertical,
                itemCount: widget.items.length + 1,
              ),
              children: [
                // 渲染标签列表（初始选中第一个）
                ...widget.items.asMap().entries.map((entry) {
                  final int index = entry.key;
                  final String item = entry.value;
                  final bool isSelected =
                      _selectedIndex == index; // 初始时index=0为true

                  return GestureDetector(
                    onTap: () => _toggleSingleSelection(index),
                    behavior: HitTestBehavior.opaque,
                    child: SizedBox(
                      height: widget.itemHeight,
                      child: Column(
                        mainAxisSize: MainAxisSize.max,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(item, style: _getTagTextStyle(isSelected)),
                        ],
                      ),
                    ),
                  );
                }).toList(),
                // 展开/收起按钮
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () => setState(() => isExpanded = !isExpanded),
                  child: SizedBox(
                    height: widget.itemHeight,
                    width: 40,
                    child: Icon(
                      isExpanded
                          ? Icons.keyboard_arrow_up
                          : Icons.keyboard_arrow_down,
                      color: widget.selectedTextColor,
                    ),
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  // 动态生成标签样式（保持不变）
  TextStyle _getTagTextStyle(bool isSelected) {
    if (widget.itemStyle != null) {
      return widget.itemStyle!.copyWith(
        color: isSelected
            ? widget.selectedTextColor
            : widget.unselectedTextColor,
      );
    }
    return TextStyle(
      fontSize: 14,
      fontWeight: FontWeight.w500,
      color: isSelected ? widget.selectedTextColor : widget.unselectedTextColor,
    );
  }
}

// 以下布局相关代码保持不变
class TagFlowET {
  static int maxRowCount = 1;
}

class TagFlowDelegate extends FlowDelegate {
  final double maxWidth;
  final double spaceHorizontal;
  final double spaceVertical;
  int maxRows;
  final bool isExpanded;
  final double itemHeight;
  final int itemCount;

  TagFlowDelegate({
    required this.maxWidth,
    required this.itemCount,
    required this.spaceHorizontal,
    required this.spaceVertical,
    required this.maxRows,
    required this.isExpanded,
    required this.itemHeight,
  }) {
    if (!isExpanded) TagFlowET.maxRowCount = maxRows;
  }

  @override
  void paintChildren(FlowPaintingContext context) {
    TagFlowET.maxRowCount = _getMaxRowCount(context);
    if (maxRows >= TagFlowET.maxRowCount) maxRows = TagFlowET.maxRowCount;

    double x = 0;
    double y = 0;
    double rowHeight = 0;
    int rowCount = 1;

    for (int i = 0; i < context.childCount; i++) {
      final childSize = context.getChildSize(i)!;
      final arrowBtnSize = context.getChildSize(context.childCount - 1)!;

      if (rowCount >= maxRows &&
          !isExpanded &&
          (x + childSize.width + arrowBtnSize.width) >= maxWidth) {
        context.paintChild(
          context.childCount - 1,
          transform: Matrix4.translationValues(x, y, 0),
        );
        break;
      }

      if (x + childSize.width > maxWidth) {
        x = 0;
        y += rowHeight + spaceVertical;
        rowHeight = 0;
        rowCount++;
      }

      if (!(i == context.childCount - 1 && isExpanded && rowCount <= maxRows)) {
        context.paintChild(i, transform: Matrix4.translationValues(x, y, 0));
      }

      x += childSize.width + spaceHorizontal;
      rowHeight = childSize.height;
    }
  }

  int _getMaxRowCount(FlowPaintingContext context) {
    double x = 0;
    int rowCount = 1;
    for (int i = 0; i < context.childCount; i++) {
      final childSize = context.getChildSize(i)!;
      final arrowSize = context.getChildSize(context.childCount - 1)!;

      if (x + childSize.width > maxWidth) {
        x = 0;
        rowCount++;
      }
      if (i == context.childCount - 1 &&
          (x + childSize.width + arrowSize.width) > maxWidth) {
        rowCount++;
      }
      x += childSize.width + spaceHorizontal;
    }
    return rowCount;
  }

  @override
  Size getSize(BoxConstraints constraints) {
    final height =
        (itemHeight * TagFlowET.maxRowCount) +
        (spaceVertical * (TagFlowET.maxRowCount - 1));
    return Size(constraints.maxWidth, height);
  }

  @override
  bool shouldRelayout(covariant FlowDelegate oldDelegate) {
    return oldDelegate != this ||
        (oldDelegate as TagFlowDelegate).isExpanded != isExpanded;
  }

  @override
  bool shouldRepaint(covariant FlowDelegate oldDelegate) {
    return oldDelegate != this ||
        (oldDelegate as TagFlowDelegate).isExpanded != isExpanded;
  }
}
